package com.code.common.annotations;

import com.code.common.enums.ResultCode;
import com.code.common.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.math.BigDecimal;

/**
 * BigDecimal 校验器
 *
 * @author tangyifei
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Constraint(validatedBy = DecimalValidator.EnumValidatorHandle.class)
public @interface DecimalValidator {

    int maxScale();

    String message() default "精度错误";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 校验器
     *
     * @author tangyifei
     */
    @Slf4j
    class EnumValidatorHandle implements ConstraintValidator<DecimalValidator, Object>, Annotation {
        private int maxScale;

        @Override
        public void initialize(DecimalValidator decimalValidator) {
            maxScale = decimalValidator.maxScale();
        }

        @Override
        public Class<? extends Annotation> annotationType() {
            return null;
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (null == value) {
                return true;
            }
            if (value instanceof BigDecimal) {
                BigDecimal bigDecimal = (BigDecimal) value;
                return bigDecimal.scale() <= maxScale;
            }
            throw new BusinessException(ResultCode.BIGDECIMAL_VALIDATOR_ERROR);
        }
    }

}
